<template>
  <div class="app-container">
    <el-row>
      <el-col :span="14" :offset="5">
        <el-card style="height: 450px">
          <div slot="header">
            <span>修改信息</span>
          </div>
          <el-row>
            <el-col :span="16">
              <!--普通表单-->
              <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules">
                <el-form-item label="剩余时长">
                  <span>{{ form.duration }}分钟</span>
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                  <span>{{ form.name }}</span>
                </el-form-item>

                <el-form-item label="用户名" prop="userName">
                  <span>{{ form.userName }}</span>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                  <el-input v-model="form.password" />
                </el-form-item>

              </el-form>
            </el-col>
          </el-row>
          <div style="margin-top: 80px; float: right">
            <el-button @click="cancelAlert">取消修改</el-button>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserById, updateInfo } from '@/api/system/user'
export default {
  name: 'PersonInfo',
  data() {
    return {
      // 表单数据
      form: {
        id: null,
        name: null,
        userName: null,
        password: null,
        duration: 0
      },
      rules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 获得user信息
    ...mapGetters(['id', 'name', 'roles'])
  },
  created() {
    getUserById(this.id).then(res => {
      if (res.status === 200) {
        this.form = res.data
      }
    })
  },
  methods: {
    // 添加和更新的提交表单
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message.error('不允许提交，请检查必填项')
          return false
        }
        // 更新记录
        updateInfo(this.form).then((res) => {
          if (res.status === 200) {
            this.$message.success('修改个人信息成功')
            this.dialogFormVisible = false // 关闭对话框
            this.$store.state.user.userName = this.form.userName
            this.$store.state.user.password = this.form.password
          } else {
            if (res.status === 501) this.$message.error(res.message)
            else this.$message.error('修改个人信息失败')
          }
        })
      })
    },

    cancelAlert() {
      getUserById(this.id).then(res => {
        if (res.status === 200) {
          this.form = res.data
        }
      })
    }
  }
}
</script>

<style scoped></style>
